from typing import List
import zlib
from utils.JSON的输入和输出 import 读取json
from utils.字符utf8长度 import getStringLen

"""
JSON转为字符串 并且输出到 JSON合并/*.txt
"""

m_iCryptoKey = 0xA2  # ! 记得修改
words: list = 读取json("output/JSON/DLG_Text.json")

decorations = 读取json("data/修饰字典/DLG_dict.json")


def startWithNum(s: str) -> bool:
    nums = ["①", "②", "③", "④", "⑤", "⑥"]
    return s[0] in nums


# 对这些word进行修饰
def modifyWord(word: str) -> dict:
    if startWithNum(word):
        return word
    trans = word
    for decoration in decorations["@3@0"]:
        trans = trans.replace(decoration, f"@3{decoration}@0")
    for decoration in decorations["@2@0"]:
        trans = trans.replace(decoration, f"@2{decoration}@0")
    return trans


words_merge_string = "\u0000" * 8  # 开始就有八个空

DLG_indx = [0]

for index, word in enumerate(words):
    source = modifyWord(word["trans"]) if word["trans"] else word["word"]
    length = getStringLen(source)
    if index == 0:
        length += 8
    space_len = 4 - length % 4
    DLG_indx.append(DLG_indx[-1] + length + space_len)  # 记录DLG_indx
    words_merge_string += source + "\u0000" * space_len

# 压缩到 DLG_text
# with open('output/JSON合并/DLG_Text.txt', 'w', encoding='utf-8') as f:
#     f.write(words_merge_string)

DLG_indx = [0, 4, 8] + DLG_indx[1:]

# print(DLG_indx)


def intTo4Hex(num: int) -> List[int]:
    res = []
    for _ in range(4):
        res.append(num % 256)
        num //= 256
    return res


DLG_indx_merge = []
for item in DLG_indx:
    DLG_indx_merge.extend(intTo4Hex(item))

# outfile = open("output/JSON合并/DLG_Indx.txt", "wb")

# for i in range(len(DLG_indx_merge)):
#     outfile.write(bytes([DLG_indx_merge[i]]))
# outfile.close()
# f.close()


# 直接加密
def encrypt(output_name, b: bytes):
    data = bytearray(zlib.compress(b))

    for i in range(len(data)):
        v = i + m_iCryptoKey + 0x23D
        v *= m_iCryptoKey
        v ^= i % 7
        data[i] ^= v & 0xFF

    with open(output_name, "wb") as f:
        f.write((data))
    f.close()


# encrypt("output/JSON合并/DLG_Text.txt", "output/JSON合并后加密/DLG_Text.txt")
# encrypt("output/JSON合并/DLG_Indx.txt", "output/JSON合并后加密/DLG_Indx.txt")

encrypt("output/加密后/DLG_Text.txt", bytes(words_merge_string, encoding="utf-8"))
encrypt("output/加密后/DLG_Indx.txt", bytes(DLG_indx_merge))
